# coding=utf-8

import datetime
import hashlib
import json
from urllib import parse
import requests

charset = 'UTF-8'
app_key = 'bc66bc72e7ca4e418bc69b2431fb5eab'
app_secret = 'db73998ac4d14fbab5406d4bad71dd7d'
username = parse.quote('中搜商城', charset)
password = hashlib.md5('111000'.encode(charset)).hexdigest()
JD_TOKEN_GRANT_TYPE_FIRST = 'password'
JD_TOKEN_GRANT_TYPE_REFRESH = 'refresh_token'
token_url = 'https://kploauth.jd.com/oauth/token?'
router = 'https://router.jd.com/api?'


def execute(method, param):

    data = {
        'method': method,
        'app_key': 'bc66bc72e7ca4e418bc69b2431fb5eab',
#        'access_token': getToken(),
        'access_token': 'babd4f27e2d74bff97bc07e9afdf788f8',
        'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'format': 'json',
        'v': '1.0',
        'param_json': param,
    }

    return doRequest(url=router, data=data)


def getToken():

    tokenRequest = "%sgrant_type=%s&app_key=%s&app_secret=%s&state=0&username=%s&password=%s" % (token_url, JD_TOKEN_GRANT_TYPE_FIRST, app_key, app_secret, username, password)
    response = doRequest(url=tokenRequest)
    return json.loads(response).get('access_token')


def doRequest(**req):
    return requests.post(url=req.get('url'), data=req.get('data')).text

if __name__ == '__main__':
    method = 'biz.product.PageNum.query'
    # method = 'biz.product.detail.query'
    param = {"sku": 102194}

    # print(execute(method=method, param=param))
    # print(getToken())

    # print(requests.get('http://ycsnail.sinaapp.com/'))
    s = json.dumps(param)
    print(type(s))
    print(type(json.loads(s)))


    u = '\u4e2d\u641c\u5546\u54c1\u6c601'

    print(u.encode().decode(charset))
    print(parse.urlparse(u))
    print(parse.urlunparse(u))

    print(parse.urldefrag(u))


